<template>
  <div class="page-cart">
    <van-nav-bar
      title="购物车"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    />

    <div class="body">
      <van-swipe-cell v-for="item in store.list" :key="item.cartid">
        <template #default>
          <MyCard
            show-checkbox
            :checked="item.flag"
            :price="item.originprice"
            :title="item.proname"
            :thumb="item.img1"
            @change="onChange(item.cartid, $event)"
            :num="item.num"
            @update:num="store.setNum(item.cartid, $event)"
          />

          <!-- <MyCard
            v-model:num="item.num"
            show-checkbox
            :checked="item.flag"
            :price="item.originprice"
            :title="item.proname"
            :thumb="item.img1"
            @change="onChange(item.cartid, $event)"
          /> -->
        </template>

        <template #right>
          <van-button class="delete-button" square type="danger" text="删除" />
        </template>
      </van-swipe-cell>
    </div>

    <div class="footer">
      <van-submit-bar :price="store.total" button-text="提交订单">
        <van-checkbox :model-value="store.isAll" @update:model-value="fn1">
          全选
        </van-checkbox>
      </van-submit-bar>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, watch } from "vue";
// 引入 my-card
import MyCard from "@/components/my-card.vue";

import { useCartStore } from "@/stores/cart";
import { useUserStore } from "@/stores/user";
import { updateCheckedAll } from "@/api/cart";

const store = useCartStore();
const userStore = useUserStore();

onMounted(() => {
  // 调用 action 获取列表数据
  store.getList();
});

const onChange = (cartid: string, isChecked: boolean) => {
  console.log("onChange", isChecked);

  // 调用 store.setChecked()
  store.setChecked(cartid, isChecked);
};

const onChangeNum = (cartid: string, num: number) => {
  // 调用store.setNum(cartid, isChecked)
  store.setNum(cartid, num);
};

const fn1 = (isChecked: boolean) => {
  // console.log("fn1", isChecked);
  // 判断是否要勾选上
  if (isChecked) {
    // 全选
    store.list = store.list.map((item) => ({
      ...item,
      flag: true,
    }));
  } else {
    // 取消反选
    store.list = store.list.map((item) => ({
      ...item,
      flag: false,
    }));
  }

  // 调用接口更新数据库的数据
  updateCheckedAll(userStore.userid, isChecked);
};

// watch(
//   () => store.list,
//   (newVal, oldVal) => {
//     console.log("hello", newVal, oldVal);
//   },
//   {
//     deep: true, // 深度监听
//   }
// );
</script>

<style lang="scss" scoped>
.delete-button {
  height: 100%;
}

// :not 否定
// .van-swipe-cell:not(:first-child) {
//   margin-top: 20px;
// }

.van-swipe-cell ~ .van-swipe-cell {
  margin-top: 20px;
}

.van-submit-bar {
  position: static;
}

.page-cart {
  display: flex;
  flex-direction: column;
  height: 100%;

  .body {
    flex: 1;
  }
}
</style>
